<template>
    <div class="btn-form"  @touchmove="handleTouchMove">
        <!-- 标题 -->
        <van-popup v-model:show="visible" position="bottom" :style="{ height: '100%' }" @open="openForm" class="form-popup">
            <div class="form-container">
                <van-nav-bar :title="typeNumber === '1' ? '确认提交' : '修改提交'" left-text="返回" left-arrow
                    @click-left="visible = false" class="nav-bar" />

                <!-- 表单 -->
                <div class="form-content" ref="formContent">
                    <van-form @submit="submit" scroll-to-error>
                        <van-cell-group inset>
                            <van-field v-model="form.created_by_name" label="工单创建人" readonly label-width="120px" />

                            <van-field v-model="form.supervisor_name" label="负责人" readonly label-width="120px" />

                            <van-field v-model="form.customer" label="FAB" readonly label-width="120px" />

                            <van-field v-model="form.reporter_name" label="客户联系人" readonly label-width="120px" />

                            <van-field v-model="form.phone_number" label="电话" readonly label-width="120px" />

                            <van-field v-model="form.email_address" label="邮箱" readonly label-width="120px" />

                            <van-field v-model="form.ticket_type_name" is-link label="工单类型" placeholder="请选择"
                                :rules="[{ required: true, message: '工单类型不能为空' }]" required @click="workTypeShow = true"
                                label-width="120px" readonly>
                                <template #input>
                                    <van-popover v-model:show="workTypeShow" :actions="workOrderActions1" @select="onSelect">
                                        <template #reference>
                                            <div>{{ form.ticket_type_name }}</div>
                                        </template>
                                    </van-popover>
                                </template>
                            </van-field>

                            <van-field v-model="form.ticket_cate_name" is-link label="工单分类" placeholder="请选择"
                                :rules="[{ required: true, message: '工单分类不能为空' }]" required @click="classifyShow = true"
                                label-width="120px" readonly>
                                <template #input>
                                    <van-popover v-model:show="classifyShow"
                                        :actions="form.ticket_type === 0 ? issueClassify : consultationClassify"
                                        @select="classifyOnSelect">
                                        <template #reference>
                                            <div>{{ form.ticket_cate_name }}</div>
                                        </template>
                                    </van-popover>
                                </template>
                            </van-field>

                            <template v-if="!form.ticket_type">
                                <van-field v-model="form.device_sn_cust_name" is-link label="客户设备编号" placeholder="请选择"
                                    :rules="[{ required: true, message: '客户设备编号不能为空' }]" required
                                    @click="deviceNumberShow = true" readonly label-width="120px" />
                                <van-popup v-model:show="deviceNumberShow" destroy-on-close position="bottom">
                                    <van-picker :columns="deviceNumberColumns" :model-value="deviceNumberValue"
                                        :columns-field-names="customFieldName" @confirm="customFieldConfirm"
                                        @cancel="deviceNumberShow = false" />
                                </van-popup>
                            </template>


                            <template v-if="!form.ticket_type">
                                <van-field v-model="form.device_status_name" is-link label="设备状态" placeholder="请选择"
                                    :rules="[{ required: true, message: '设备状态不能为空' }]" required @click="deviceStatusShow = true"
                                    label-width="120px">
                                    <template #input>
                                        <van-popover v-model:show="deviceStatusShow" :actions="equipmentActions"
                                            @select="deviceSelect">
                                            <template #reference>
                                                <div>{{ form.device_status_name }}</div>
                                            </template>
                                        </van-popover>
                                    </template>
                                </van-field>
                            </template>

                            <van-field v-model="form.device_type" label="设备型号" readonly label-width="120px"
                                v-if="!form.ticket_type" />

                            <van-field v-model="form.device_sn" label="设备序列号" readonly label-width="120px"
                                v-if="!form.ticket_type" />

                            <van-field v-model="form.device_warranty" label="设备保修到期日" readonly label-width="120px"
                                v-if="!form.ticket_type" />

                            <van-field v-model="form.component_warranty" label="部件保修到期日" readonly label-width="120px"
                                v-if="!form.ticket_type" />

                            <van-field v-model="form.ticket_title" label="标题" placeholder="请输入标题"
                                :rules="[{ required: true, message: '标题不能为空' }]" required label-width="120px" />

                            <van-field v-model="form.to_user_name" label="TO" readonly label-width="120px" />

                            <van-field v-model="form.cc_users_name" is-link label="CC" placeholder="点击选择抄送人" @click="ccClick"
                                readonly label-width="120px" />

                            <van-cell-group inset style="margin: 0;">
                                <van-field v-model="form.ticket_desc" rows="2" autosize label="详细描述" type="textarea"
                                    maxlength="1000" placeholder="请输入" show-word-limit
                                    :rules="[{ required: true, message: '详细描述不能为空' }]" required label-width="120px" />
                            </van-cell-group>

                        </van-cell-group>

                        <van-field name="uploader" label="附件" style="padding-left: 35px;" readonly
                            v-if="(!cieType && typeNumber === '2') || (typeNumber === '1' && cieType)">
                            <template #input v-if="!cieType && typeNumber === '2'">
                                <van-uploader :max-count="5"
                                    accept=".docx,.xlsx,.pptx,.txt,.pdf,.jpg,.png,.zip,.xls,.xlsm,.doc,.docm,.ppt,.pptm,.pps"
                                    :after-read="afterRead">
                                    <div class="work-uploader">上传...</div>
                                </van-uploader>
                            </template>
                        </van-field>

                        <div v-if="!cieType && typeNumber === '2'">
                            <template v-for="item in form.attachment" :key="item.file_path">
                                <div class="work-file">
                                    <div class="work-file-name" @click="previewFile(item)">
                                        <u>{{ item.file_name }}</u>
                                    </div>
                                    <div @click="deleteFile(item.file_path)"><van-icon name="cross" /></div>
                                </div>
                            </template>
                        </div>
                    </van-form>
                </div>

                <div class="submit-button">
                    <van-button round block type="primary" native-type="submit" color="#bf1920" @click="submit">
                        提交
                    </van-button>
                </div>
            </div>
        </van-popup>

        <!-- 通讯录 -->
        <contactsPopUp v-model="ccShow" parameter="cc" operate_type="transfer" :ticket_number="form.ticket_number"
            :commonly-list-id="commonlyListId" @checkboxChange="checkboxChange" />
    </div>
</template>

<script setup lang='ts'>
import dayjs from 'dayjs';
import useKeyboard from '@/utils/keyboard'
import { download } from '@/utils/downloadUrl';
import contactsPopUp from '@/components/ContactsPopUp.vue';
import { CommonlyType, SubMitType } from '@/api/worksheets/type';
import { getDeviceNumber, workAttachmentDownload, workAttachmentUpload, workClassify, workDeviceNumber, workFormView } from '@/api/worksheets';

const prop = defineProps<{
    commitData: SubMitType//回显数据
    typeNumber: string//1：确认提交  2：修改提交
    fabId: any//设备id
}>()

const emit = defineEmits<{
    (e: 'success'): void
}>()

const { hideKeyboard } = useKeyboard()

const cieType = computed(() => {
    return Number(localStorage.getItem('mobile_userType'))
})

const visible = defineModel<boolean>('modelValue')

const ccShow = ref(false)

const workTypeShow = ref(false)

const classifyShow = ref(false)

const deviceNumberShow = ref(false)

const deviceStatusShow = ref(false)

const deviceNumberValue = ref([]);

const ccList = ref<CommonlyType[]>([])

const commonlyListId = ref<string[]>([])

const deviceNumberColumns = ref<CommonlyType[]>([])

const form = ref<SubMitType>({} as SubMitType)

const customFieldName = {
    text: 'name',
    value: 'id'
};

//设备状态
const equipmentActions = ref([
    {
        text: '设备可以运行',
        value: '0'
    },
    {
        text: '设备无法运行',
        value: '1'
    },
])

//工单类型
const workOrderActions1 = [
    { text: '问题', value: 0 },
    { text: '咨询&要求', value: 1 },
];

//工单分类/问题
const issueClassify = ref([
    {
        text: '故障维修',
        value: 0
    },
    {
        text: '精度',
        value: 1
    },
    {
        text: '产品咨询',
        value: 2
    }
])

//工单分类/咨询&要求
const consultationClassify = ref([
    {
        text: '视频',
        value: 3
    },
    {
        text: '资料',
        value: 4
    },
    {
        text: '部件',
        value: 5
    }
])

const uploadType = [
    '.docx',
    '.xlsx',
    '.pptx',
    '.txt',
    '.pdf',
    '.jpg',
    '.png',
    '.zip',
    '.xls',
    '.xlsm',
    '.doc',
    '.docm',
    '.ppt',
    '.pptm',
    '.pps'
]

const formContent = ref<HTMLElement | null>(null);

// 监听键盘事件
onMounted(() => {
    window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
});

// 处理键盘弹出/收起
const handleResize = () => {
    if (!formContent.value) return;
    
    // 延迟执行以确保DOM已更新
    setTimeout(() => {
        const scrollHeight = formContent.value?.scrollHeight || 0;
        const clientHeight = formContent.value?.clientHeight || 0;
        
        if (scrollHeight > clientHeight) {
            formContent.value.scrollTop = 0;
        }
    }, 100);
};

//打开弹窗
const openForm = () => {
    deviceSnChange(prop.fabId)

    dataEcho()
}

//选择工单类型
const onSelect = (val: { text: string, value: number }) => {
    form.value.ticket_type_name = val.text

    form.value.ticket_type = val.value
}

//选择工单分类
const classifyOnSelect = (val: { text: string, value: number }) => {
    form.value.ticket_cate_name = val.text

    form.value.ticket_cate = val.value

    workTypeChange(val.value)
}

//选择设备状态
const deviceSelect = (val: { text: string, value: number }) => {
    form.value.device_status_name = val.text

    form.value.device_status = val.value

}

//工单分类获取负责人和To
const workTypeChange = async (val: number) => {
    const params = {
        customer: form.value.customer_id,
        ticket_type: form.value.ticket_type,
        ticket_cate: val
    }

    try {
        const res: any = await workClassify(params)

        form.value.supervisor = res.data.id || null

        form.value.supervisor_name = res.data.name || ''

        form.value.to_user = res.data.id || null

        form.value.to_user_name = res.data.name || ''

    } catch (err) {
        //
    }
}

//客户设备编号选择
const customFieldConfirm = ({ selectedValues, selectedOptions }) => {
    form.value.device_sn_cust_name = selectedOptions[0]?.name;
    form.value.device_sn_cust = selectedOptions[0]?.id;
    deviceNumberValue.value = selectedValues;
    deviceNumberShow.value = false;
    numberSnChange(selectedOptions[0]?.id)
};


//通过客户设备编号获取对应数据
const numberSnChange = async (val: number) => {

    try {
        const res: any = await getDeviceNumber({ device_sn_cust: val })

        form.value.device_type = res.data.device_type

        form.value.device_sn = res.data.device_sn

        form.value.device_warranty = res.data.device_warranty

        form.value.component_warranty = res.data.component_warranty

    } catch (err) {
        //
    }
}

//获取客户设备编号
const deviceSnChange = async (val: number) => {
    if (!val) return

    try {
        const res: any = await workDeviceNumber({ customer_id: val })

        deviceNumberColumns.value = res.device_list || []

    } catch (err) {
        //
    }
}


//获取cc数据
const checkboxChange = async (val: CommonlyType[]) => {
    ccList.value = val || []

    form.value.cc_users = val.map((item: CommonlyType) => item.username)

    form.value.cc_users_name = val.map((item: CommonlyType) => item.name).join(',')
}

// 文件上传
const afterRead = async (uploadFile: any) => {

    if (form.value.attachment.length >= 5) {
        showFailToast('最多上传5个文件')
        return
    }

    //  文件大小不能超过 10MB
    const isLt2M = uploadFile.file.size ? uploadFile.file.size / 1024 / 1024 <= 10 : true

    //上传文件是否包含.
    const Suffix = uploadFile.file.name.includes('.')

    //取文件后缀
    const fileSuffix = uploadFile.file.name.split('.')[uploadFile.file.name.split('.').length - 1].toLowerCase()

    // 不支持上传的文件类型
    const notSupportedType = uploadType.includes('.' + fileSuffix)

    if (!isLt2M) {
        showFailToast('上传文件大小不能超过 10MB!');
        return
    } else if (!notSupportedType || !Suffix) {
        showFailToast('不支持上传该文件类型');
        return
    }

    const nativeFile: File = uploadFile.file as unknown as File

    const res: any = await workAttachmentUpload({ file_name: nativeFile.name, type: nativeFile.type })

    const params = {
        uid: nativeFile.lastModified,
        file_name: nativeFile.name,
        file_path: res.file_path
    }

    form.value.attachment.push(params)

    const xhr = new XMLHttpRequest()

    xhr.open('PUT', res.upload_url, true)

    xhr.setRequestHeader('Content-Type', nativeFile?.type as string)

    xhr.send(nativeFile)
}

//删除附件
const deleteFile = (path: string) => {
    form.value.attachment = form.value.attachment.filter((item: any) => item.file_path !== path)
}

//附件下载
const previewFile = async (items: any) => {

    const file: any = form.value.attachment.find((item: any) => item.uid === items.uid)

    const params = {
        file_path: file.file_path,
        file_name: file.file_name
    }

    const res: any = await workAttachmentDownload({ file_path: params.file_path })

    download(res.download_url, params.file_name)

}

// 点击cc
const ccClick = () => {
    ccShow.value = true

    commonlyListId.value = ccList.value.map((item: CommonlyType) => item.id) || []
}

//数据回显
const dataEcho = () => {
    Object.assign(form.value, prop.commitData)

    form.value.device_warranty = dayjs(form.value.device_warranty).format('YYYY-MM-DD')

    form.value.component_warranty = dayjs(form.value.component_warranty).format('YYYY-MM-DD')

    deviceNumberValue.value = [form.value.device_sn_cust]

    ccList.value = prop.commitData.cc_users_list || []

    form.value.cc_users_name = prop.commitData.cc_users_list.map((item) => item.name).join(',')

    form.value.cc_users = prop.commitData.cc_users_list.map((item: CommonlyType) => item.username)
}

//提交
const submit = async () => {
    try {

        const res: any = await workFormView(form.value)

        visible.value = false

        emit('success')

        showSuccessToast(res.message);


    } catch (err) {
        // errError(err)
    }
}

// 页面滚动时关闭键盘
const handleTouchMove = () => {
    hideKeyboard()
}
</script>

<style lang="scss" scoped>
.btn-form {
    width: 100%;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: none;
    background: #fff;
    :deep(.form-popup) {
        .van-popup__content {
            height: 100%;
            display: flex;
            flex-direction: column;
        }
    }

    .form-container {
        height: 100%;
        display: flex;
        flex-direction: column;
        background: #fff;
    }

    .nav-bar {
        flex-shrink: 0;
        background: #fff;
    }

    .form-content {
        flex: 1;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        overscroll-behavior: none;
        padding-bottom: 16px;
        position: relative;
        &::-webkit-scrollbar {
            display: none;
        }
    }

    .submit-button {
        flex-shrink: 0;
        padding: 10px;
        background: #fff;
        border-top: 1px solid #f5f5f5;
        // background: red;
    }

    :deep(.van-popup) {
        background: #fff;
        &::-webkit-scrollbar {
            display: none;
        }
    }

    :deep(.van-form) {
        background: #fff;
        min-height: 100%;
        &::-webkit-scrollbar {
            display: none;
        }
    }

    .work-uploader {
        width: 60px;
        height: 25px;
        background: #d9d9d9;
        text-align: center;
        line-height: 25px;
        border-radius: 10px;
        font-size: 12px;
        font-weight: 600;
        margin-top: 2px;
    }

    .work-file {
        display: flex;
        align-items: center;
        font-size: 14px;
        margin-top: 10px;
        padding-left: 140px;

        .work-file-name {
            width: 180px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            color: #0349e7;
        }
    }

    :deep(.van-cell-group) {
        background: #fff;
        .van-cell {
            background: #fff;
            .van-field__label--required:before {
                margin-left: -7px;
            }
        }
    }

    :deep(.van-nav-bar__title) {
        font-size: 15px;
    }
}

// 全局样式
:deep(.van-popup) {
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: none;
    background: #fff;
    &::-webkit-scrollbar {
        display: none;
    }
}

// 添加全局样式
:deep(*) {
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    user-select: none;
}
</style>